<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="java,">










<meta name="description" content="写在前面 闭锁 信号量 栅栏 阻塞队列   CAS还是借助native的方法实现.  CAS是乐观锁, 比较底层, 性能较高, 但是CAS中有大量的自旋操作, 又会消耗性能, 世上没有完美的解决方案  CountDownLatch 与 CyclicBarrier 区别. CountDownLatch 可以多个线程都持有这个对象后调用await方法等待,   当计数器为0的时候, 就会唤醒所有的等">
<meta name="keywords" content="java">
<meta property="og:type" content="article">
<meta property="og:title" content="线程同步工具类">
<meta property="og:url" content="https://blog.xiezc.xyz/2019/03/22/java/线程同步工具类/index.html">
<meta property="og:site_name" content="xiezc的小站">
<meta property="og:description" content="写在前面 闭锁 信号量 栅栏 阻塞队列   CAS还是借助native的方法实现.  CAS是乐观锁, 比较底层, 性能较高, 但是CAS中有大量的自旋操作, 又会消耗性能, 世上没有完美的解决方案  CountDownLatch 与 CyclicBarrier 区别. CountDownLatch 可以多个线程都持有这个对象后调用await方法等待,   当计数器为0的时候, 就会唤醒所有的等">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:updated_time" content="2019-04-04T14:25:06.077Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="线程同步工具类">
<meta name="twitter:description" content="写在前面 闭锁 信号量 栅栏 阻塞队列   CAS还是借助native的方法实现.  CAS是乐观锁, 比较底层, 性能较高, 但是CAS中有大量的自旋操作, 又会消耗性能, 世上没有完美的解决方案  CountDownLatch 与 CyclicBarrier 区别. CountDownLatch 可以多个线程都持有这个对象后调用await方法等待,   当计数器为0的时候, 就会唤醒所有的等">
<meta name="twitter:image" content="https://common.cnblogs.com/images/copycode.gif">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://blog.xiezc.xyz/2019/03/22/java/线程同步工具类/">





  <title>线程同步工具类 | xiezc的小站</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?8ae02d8cf311eabbae2621ff2d51a260";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">xiezc的小站</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">xiezc的小站</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://blog.xiezc.xyz/2019/03/22/java/线程同步工具类/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xiezc">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="xiezc的小站">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">线程同步工具类</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-03-22T16:47:47+08:00">
                2019-03-22
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2019/03/22/java/线程同步工具类/" class="leancloud_visitors" data-flag-title="线程同步工具类">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <ul>
<li><a href="https://www.cnblogs.com/chenpi/p/5358579.html#_label0" target="_blank" rel="noopener">写在前面</a></li>
<li><a href="https://www.cnblogs.com/chenpi/p/5358579.html#_label1" target="_blank" rel="noopener">闭锁</a></li>
<li><a href="https://www.cnblogs.com/chenpi/p/5358579.html#_label2" target="_blank" rel="noopener">信号量</a></li>
<li><a href="https://www.cnblogs.com/chenpi/p/5358579.html#_label3" target="_blank" rel="noopener">栅栏</a></li>
<li><a href="https://www.cnblogs.com/chenpi/p/5358579.html#_label4" target="_blank" rel="noopener">阻塞队列</a></li>
</ul>
<blockquote>
<p>CAS还是借助native的方法实现.  CAS是乐观锁, 比较底层, 性能较高, 但是CAS中有大量的自旋操作, 又会消耗性能, 世上没有完美的解决方案</p>
</blockquote>
<h4 id="CountDownLatch-与-CyclicBarrier-区别"><a href="#CountDownLatch-与-CyclicBarrier-区别" class="headerlink" title="CountDownLatch 与 CyclicBarrier 区别."></a>CountDownLatch 与 CyclicBarrier 区别.</h4><blockquote>
<p>CountDownLatch 可以多个线程都持有这个对象后调用await方法等待,  </p>
<p>当计数器为0的时候, 就会唤醒所有的等待的线程</p>
</blockquote>
<blockquote>
<p>CyclicBarrier  没有计数器(显示的), 只有规定个数的线程都到了await状态后, 才会把这规定个数的线程一起唤醒继续执行.  感觉就像 所有的选手都到了统一的位置后再次开始跑</p>
</blockquote>
<h1 id="写在前面"><a href="#写在前面" class="headerlink" title="写在前面"></a>写在前面</h1><p>同步工具类主要包括闭锁（如CountDownLatch），栅栏（如CyclicBarrier），信号量（如Semaphore）和阻塞队列（如LinkedBlockingQueue）等；</p>
<p>使用同步工具类可以协调线程的控制流；</p>
<p>同步工具类封装了一些状态，这些状态决定线程是继续执行还是等待，此外同步工具类还提供了修改状态的方法；</p>
<p>下面将简单介绍以上同步工具类；</p>
<h1 id="闭锁"><a href="#闭锁" class="headerlink" title="闭锁"></a>闭锁</h1><p>可以让一个线程等待一组事件发生后（不一定要线程结束）继续执行；</p>
<blockquote>
<p>常用与把某个大任务拆分成几个小的任务去执行,  需要等待所有的小任务完成后才能继续执行下个大任务</p>
</blockquote>
<p>以CountDownLatch为例，内部包含一个计数器，一开始初始化为一个整数（事件个数），发生一个事件后，调用countDown方法，计数器减1，await用于等待计数器为0后继续执行当前线程；</p>
<p>举个例子如下，main线程等待其它子线程的事件发生后继续执行main线程：</p>
<p><a href="javascript:void(0" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a>;)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line">package concurrency;</span><br><span class="line"></span><br><span class="line">import java.text.SimpleDateFormat;</span><br><span class="line">import java.util.Date;</span><br><span class="line">import java.util.concurrent.CountDownLatch;</span><br><span class="line">import java.util.concurrent.ExecutorService;</span><br><span class="line">import java.util.concurrent.Executors;</span><br><span class="line">import java.util.concurrent.TimeUnit;</span><br><span class="line"></span><br><span class="line">class TaskTest implements Runnable &#123;</span><br><span class="line"></span><br><span class="line">    private CountDownLatch latch;</span><br><span class="line">    private int sleepTime;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * </span><br><span class="line">     */</span><br><span class="line">    public TaskTest(int sleepTime, CountDownLatch latch) &#123;</span><br><span class="line">        this.sleepTime = sleepTime;</span><br><span class="line">        this.latch = latch;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * @see java.lang.Runnable#run()</span><br><span class="line">     */</span><br><span class="line">    @Override</span><br><span class="line">    public void run() &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            CountDownLatchTest.print(&quot; is running。&quot;);</span><br><span class="line">            TimeUnit.MILLISECONDS.sleep(sleepTime);</span><br><span class="line">            CountDownLatchTest.print(&quot; finished。&quot;);</span><br><span class="line">            //计数器减减</span><br><span class="line">            latch.countDown();</span><br><span class="line">        &#125; catch (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">public class CountDownLatchTest &#123;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        int count = 10;</span><br><span class="line">        final CountDownLatch latch = new CountDownLatch(count);</span><br><span class="line">        ExecutorService es = Executors.newFixedThreadPool(count);</span><br><span class="line">        for (int i = 0; i &lt; count; i++) &#123;</span><br><span class="line">            es.execute(new TaskTest((i + 1) * 1000, latch));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        try &#123;</span><br><span class="line">            CountDownLatchTest.print(&quot; waiting...&quot;);</span><br><span class="line">            //主线程等待其它事件发生</span><br><span class="line">            latch.await();</span><br><span class="line">            //其它事件已发生，继续执行主线程</span><br><span class="line">            CountDownLatchTest.print(&quot; continue。。。&quot;);</span><br><span class="line">        &#125; catch (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; finally &#123;</span><br><span class="line">            es.shutdown();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    public static void print(String str)&#123;</span><br><span class="line">        SimpleDateFormat dfdate = new SimpleDateFormat(&quot;HH:mm:ss&quot;);</span><br><span class="line">        System.out.println(&quot;[&quot; + dfdate.format(new Date()) + &quot;]&quot; + Thread.currentThread().getName() + str);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><a href="javascript:void(0" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a>;)</p>
<p>结果打印如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">`[09:41:43]pool-1-thread-1 ``is` `running。``[09:41:43]pool-1-thread-6 ``is` `running。``[09:41:43]main waiting...``[09:41:43]pool-1-thread-10 ``is` `running。``[09:41:43]pool-1-thread-4 ``is` `running。``[09:41:43]pool-1-thread-5 ``is` `running。``[09:41:43]pool-1-thread-2 ``is` `running。``[09:41:43]pool-1-thread-3 ``is` `running。``[09:41:43]pool-1-thread-7 ``is` `running。``[09:41:43]pool-1-thread-8 ``is` `running。``[09:41:43]pool-1-thread-9 ``is` `running。``[09:41:44]pool-1-thread-1 finished。``[09:41:45]pool-1-thread-2 finished。``[09:41:46]pool-1-thread-3 finished。``[09:41:47]pool-1-thread-4 finished。``[09:41:48]pool-1-thread-5 finished。``[09:41:49]pool-1-thread-6 finished。``[09:41:50]pool-1-thread-7 finished。``[09:41:51]pool-1-thread-8 finished。``[09:41:52]pool-1-thread-9 finished。``[09:41:53]pool-1-thread-10 finished。``[09:41:53]main ``continue``。。。`</span><br></pre></td></tr></table></figure>
<p> 此外，FutureTask也可用作闭锁，其get方法会等待任务完成后返回结果，否则一直阻塞直到任务完成；</p>
<h1 id="信号量"><a href="#信号量" class="headerlink" title="信号量"></a>信号量</h1><blockquote>
<p>控制某个资源的并发访问的线程数量, 超过信号量后就会阻塞</p>
</blockquote>
<p>控制同时执行某个指定操作的数量，常用于实现资源池，如数据库连接池，线程池…<br>以Semaphore为例，其内部维护一组资源，可以通过构造函数指定数目，其它线程在执行的时候，可以通过acquire方法获取资源，有的话，继续执行（使用结束后释放资源），没有资源的话将阻塞直到有其它线程调用release方法释放资源；</p>
<p>举个例子，如下代码，十个线程竞争三个资源，一开始有三个线程可以直接运行，剩下的七个线程只能阻塞等到其它线程使用资源完毕才能执行；</p>
<p><a href="javascript:void(0" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a>;)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line">package concurrency;</span><br><span class="line"></span><br><span class="line">import java.text.SimpleDateFormat;</span><br><span class="line">import java.util.Date;</span><br><span class="line">import java.util.concurrent.ExecutorService;</span><br><span class="line">import java.util.concurrent.Executors;</span><br><span class="line">import java.util.concurrent.Semaphore;</span><br><span class="line">import java.util.concurrent.TimeUnit;</span><br><span class="line"></span><br><span class="line">public class SemaphoreTest &#123;</span><br><span class="line">    </span><br><span class="line">    public static void print(String str)&#123;</span><br><span class="line">        SimpleDateFormat dfdate = new SimpleDateFormat(&quot;HH:mm:ss&quot;);</span><br><span class="line">        System.out.println(&quot;[&quot; + dfdate.format(new Date()) + &quot;]&quot; + Thread.currentThread().getName() + str);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        // 线程数目</span><br><span class="line">        int threadCount = 10;</span><br><span class="line">        // 资源数目</span><br><span class="line">        Semaphore semaphore = new Semaphore(3);</span><br><span class="line">        </span><br><span class="line">        ExecutorService es = Executors.newFixedThreadPool(threadCount);</span><br><span class="line"></span><br><span class="line">        // 启动若干线程</span><br><span class="line">        for (int i = 0; i &lt; threadCount; i++)</span><br><span class="line">            es.execute(new ConsumeResourceTask((i + 1) * 1000, semaphore));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">class ConsumeResourceTask implements Runnable &#123;</span><br><span class="line">    private Semaphore semaphore;</span><br><span class="line">    private int sleepTime;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">         * </span><br><span class="line">         */</span><br><span class="line">    public ConsumeResourceTask(int sleepTime, Semaphore semaphore) &#123;</span><br><span class="line">        this.sleepTime = sleepTime;</span><br><span class="line">        this.semaphore = semaphore;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void run() &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            //获取资源</span><br><span class="line">            semaphore.acquire();</span><br><span class="line">            SemaphoreTest.print(&quot; 占用一个资源...&quot;);</span><br><span class="line">            TimeUnit.MILLISECONDS.sleep(sleepTime);</span><br><span class="line">            SemaphoreTest.print(&quot; 资源使用结束，释放资源&quot;);</span><br><span class="line">            //释放资源</span><br><span class="line">            semaphore.release();</span><br><span class="line">        &#125; catch (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><a href="javascript:void(0" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a>;)</p>
<p><a href="javascript:void(0" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a>;)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">[10:30:11]pool-1-thread-1 占用一个资源...</span><br><span class="line">[10:30:11]pool-1-thread-2 占用一个资源...</span><br><span class="line">[10:30:11]pool-1-thread-3 占用一个资源...</span><br><span class="line">[10:30:12]pool-1-thread-1 资源使用结束，释放资源</span><br><span class="line">[10:30:12]pool-1-thread-4 占用一个资源...</span><br><span class="line">[10:30:13]pool-1-thread-2 资源使用结束，释放资源</span><br><span class="line">[10:30:13]pool-1-thread-5 占用一个资源...</span><br><span class="line">[10:30:14]pool-1-thread-3 资源使用结束，释放资源</span><br><span class="line">[10:30:14]pool-1-thread-8 占用一个资源...</span><br><span class="line">[10:30:16]pool-1-thread-4 资源使用结束，释放资源</span><br><span class="line">[10:30:16]pool-1-thread-6 占用一个资源...</span><br><span class="line">[10:30:18]pool-1-thread-5 资源使用结束，释放资源</span><br><span class="line">[10:30:18]pool-1-thread-9 占用一个资源...</span><br><span class="line">[10:30:22]pool-1-thread-8 资源使用结束，释放资源</span><br><span class="line">[10:30:22]pool-1-thread-7 占用一个资源...</span><br><span class="line">[10:30:22]pool-1-thread-6 资源使用结束，释放资源</span><br><span class="line">[10:30:22]pool-1-thread-10 占用一个资源...</span><br><span class="line">[10:30:27]pool-1-thread-9 资源使用结束，释放资源</span><br><span class="line">[10:30:29]pool-1-thread-7 资源使用结束，释放资源</span><br><span class="line">[10:30:32]pool-1-thread-10 资源使用结束，释放资源</span><br></pre></td></tr></table></figure>
<p><a href="javascript:void(0" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a>;)</p>
<h1 id="栅栏"><a href="#栅栏" class="headerlink" title="栅栏"></a>栅栏</h1><p>栅栏用于等待其它线程，且会阻塞自己当前线程；</p>
<p>所有线程必须同时到达栅栏位置后，才能继续执行；</p>
<p>举个例子如下：</p>
<p><a href="javascript:void(0" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a>;)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line">package concurrency;</span><br><span class="line"></span><br><span class="line">import java.text.SimpleDateFormat;</span><br><span class="line">import java.util.Date;</span><br><span class="line">import java.util.concurrent.BrokenBarrierException;</span><br><span class="line">import java.util.concurrent.CyclicBarrier;</span><br><span class="line">import java.util.concurrent.ExecutorService;</span><br><span class="line">import java.util.concurrent.Executors;</span><br><span class="line">import java.util.concurrent.TimeUnit;</span><br><span class="line"></span><br><span class="line">class CyclicBarrierTaskTest implements Runnable &#123;</span><br><span class="line">    private CyclicBarrier cyclicBarrier;</span><br><span class="line"></span><br><span class="line">    private int timeout;</span><br><span class="line"></span><br><span class="line">    public CyclicBarrierTaskTest(CyclicBarrier cyclicBarrier, int timeout) &#123;</span><br><span class="line">        this.cyclicBarrier = cyclicBarrier;</span><br><span class="line">        this.timeout = timeout;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void run() &#123;</span><br><span class="line">        TestCyclicBarrier.print(&quot; 正在running...&quot;);</span><br><span class="line">        try &#123;</span><br><span class="line">            TimeUnit.MILLISECONDS.sleep(timeout);</span><br><span class="line">            TestCyclicBarrier.print(&quot; 到达栅栏处，等待其它线程到达&quot;);</span><br><span class="line">            cyclicBarrier.await();</span><br><span class="line">        &#125; catch (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; catch (BrokenBarrierException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        TestCyclicBarrier.print(&quot; 所有线程到达栅栏处，继续执行各自线程任务...&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">public class TestCyclicBarrier &#123;</span><br><span class="line"></span><br><span class="line">    public static void print(String str) &#123;</span><br><span class="line">        SimpleDateFormat dfdate = new SimpleDateFormat(&quot;HH:mm:ss&quot;);</span><br><span class="line">        System.out.println(&quot;[&quot; + dfdate.format(new Date()) + &quot;]&quot;</span><br><span class="line">                + Thread.currentThread().getName() + str);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        int count = 5;</span><br><span class="line">        </span><br><span class="line">        ExecutorService es = Executors.newFixedThreadPool(count);</span><br><span class="line"></span><br><span class="line">        CyclicBarrier barrier = new CyclicBarrier(count, new Runnable() &#123;</span><br><span class="line"></span><br><span class="line">            @Override</span><br><span class="line">            public void run() &#123;</span><br><span class="line">                TestCyclicBarrier.print(&quot; 所有线程到达栅栏处,可以在此做一些处理...&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        for (int i = 0; i &lt; count; i++)</span><br><span class="line">            es.execute(new CyclicBarrierTaskTest(barrier, (i + 1) * 1000));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><a href="javascript:void(0" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a>;)</p>
<p><a href="javascript:void(0" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a>;)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">[11:07:00]pool-1-thread-2 正在running...</span><br><span class="line">[11:07:00]pool-1-thread-1 正在running...</span><br><span class="line">[11:07:00]pool-1-thread-5 正在running...</span><br><span class="line">[11:07:00]pool-1-thread-3 正在running...</span><br><span class="line">[11:07:00]pool-1-thread-4 正在running...</span><br><span class="line">[11:07:01]pool-1-thread-1 到达栅栏处，等待其它线程到达</span><br><span class="line">[11:07:02]pool-1-thread-2 到达栅栏处，等待其它线程到达</span><br><span class="line">[11:07:03]pool-1-thread-3 到达栅栏处，等待其它线程到达</span><br><span class="line">[11:07:04]pool-1-thread-4 到达栅栏处，等待其它线程到达</span><br><span class="line">[11:07:05]pool-1-thread-5 到达栅栏处，等待其它线程到达</span><br><span class="line">[11:07:05]pool-1-thread-5 所有线程到达栅栏处,可以在此做一些处理...</span><br><span class="line">[11:07:05]pool-1-thread-1 所有线程到达栅栏处，继续执行各自线程任务...</span><br><span class="line">[11:07:05]pool-1-thread-2 所有线程到达栅栏处，继续执行各自线程任务...</span><br><span class="line">[11:07:05]pool-1-thread-5 所有线程到达栅栏处，继续执行各自线程任务...</span><br><span class="line">[11:07:05]pool-1-thread-3 所有线程到达栅栏处，继续执行各自线程任务...</span><br><span class="line">[11:07:05]pool-1-thread-4 所有线程到达栅栏处，继续执行各自线程任务...</span><br></pre></td></tr></table></figure>
<p><a href="javascript:void(0" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a>;)</p>
<h1 id="阻塞队列"><a href="#阻塞队列" class="headerlink" title="阻塞队列"></a>阻塞队列</h1><p>阻塞队列提供了可阻塞的入队和出对操作，如果队列满了，入队操作将阻塞直到有空间可用，如果队列空了，出队操作将阻塞直到有元素可用；</p>
<p>队列可以为有界和无界队列，无界队列不会满，因此入队操作将不会阻塞；</p>
<p>下面将使用阻塞队列LinkedBlockingQueue举个生产者-消费者例子，生产者每隔1秒生产1个产品，然后有6个消费者在消费产品，可以发现，每隔1秒，只有一个消费者能够获取到产品消费，其它线程只能等待…</p>
<p>如下代码：</p>
<p><a href="javascript:void(0" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a>;)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line">package concurrency;</span><br><span class="line"></span><br><span class="line">import java.text.SimpleDateFormat;</span><br><span class="line">import java.util.Date;</span><br><span class="line">import java.util.concurrent.BlockingQueue;</span><br><span class="line">import java.util.concurrent.LinkedBlockingQueue;</span><br><span class="line">import java.util.concurrent.TimeUnit;</span><br><span class="line"></span><br><span class="line">//生产者</span><br><span class="line">public class Producer implements Runnable &#123;</span><br><span class="line">    private final BlockingQueue&lt;String&gt; fileQueue;</span><br><span class="line"></span><br><span class="line">    public Producer(BlockingQueue&lt;String&gt; queue) &#123;</span><br><span class="line">        this.fileQueue = queue;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void run() &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            while (true) &#123;</span><br><span class="line">                TimeUnit.MILLISECONDS.sleep(1000);</span><br><span class="line">                String produce = this.produce();</span><br><span class="line">                System.out.println(Thread.currentThread() + &quot;生产：&quot; + produce);</span><br><span class="line">                fileQueue.put(produce);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125; catch (InterruptedException e) &#123;</span><br><span class="line">            Thread.currentThread().interrupt();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public String produce() &#123;</span><br><span class="line">        SimpleDateFormat dfdate = new SimpleDateFormat(&quot;HH:mm:ss&quot;);</span><br><span class="line">        return dfdate.format(new Date());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        BlockingQueue&lt;String&gt; queue = new LinkedBlockingQueue&lt;String&gt;(10);</span><br><span class="line"></span><br><span class="line">        for (int i = 0; i &lt; 1; i++) &#123;</span><br><span class="line">            new Thread(new Producer(queue)).start();</span><br><span class="line">        &#125;</span><br><span class="line">        for (int i = 0; i &lt; 6; i++) &#123;</span><br><span class="line">            new Thread(new Consumer(queue)).start();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 消费者</span><br><span class="line">class Consumer implements Runnable &#123;</span><br><span class="line">    private final BlockingQueue&lt;String&gt; queue;</span><br><span class="line"></span><br><span class="line">    public Consumer(BlockingQueue&lt;String&gt; queue) &#123;</span><br><span class="line">        this.queue = queue;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void run() &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            while (true) &#123;</span><br><span class="line">                TimeUnit.MILLISECONDS.sleep(1000);</span><br><span class="line">                System.out.println(Thread.currentThread() + &quot;prepare 消费&quot;);</span><br><span class="line">                System.out.println(Thread.currentThread() + &quot;starting：&quot;</span><br><span class="line">                        + queue.take());</span><br><span class="line">                System.out.println(Thread.currentThread() + &quot;end 消费&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; catch (InterruptedException e) &#123;</span><br><span class="line">            Thread.currentThread().interrupt();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><a href="javascript:void(0" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a>;)</p>
<p><a href="javascript:void(0" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a>;)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">Thread[Thread-1,5,main]prepare 消费</span><br><span class="line">Thread[Thread-3,5,main]prepare 消费</span><br><span class="line">Thread[Thread-4,5,main]prepare 消费</span><br><span class="line">Thread[Thread-2,5,main]prepare 消费</span><br><span class="line">Thread[Thread-6,5,main]prepare 消费</span><br><span class="line">Thread[Thread-5,5,main]prepare 消费</span><br><span class="line">Thread[Thread-0,5,main]生产：11:36:36</span><br><span class="line">Thread[Thread-1,5,main]starting：11:36:36</span><br><span class="line">Thread[Thread-1,5,main]end 消费</span><br><span class="line">Thread[Thread-1,5,main]prepare 消费</span><br><span class="line">Thread[Thread-0,5,main]生产：11:36:37</span><br><span class="line">Thread[Thread-4,5,main]starting：11:36:37</span><br><span class="line">Thread[Thread-4,5,main]end 消费</span><br><span class="line">Thread[Thread-4,5,main]prepare 消费</span><br><span class="line">Thread[Thread-0,5,main]生产：11:36:38</span><br><span class="line">Thread[Thread-3,5,main]starting：11:36:38</span><br><span class="line">Thread[Thread-3,5,main]end 消费</span><br><span class="line">...</span><br></pre></td></tr></table></figure>
<p><a href="javascript:void(0" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a>;)</p>
<p> 参考资料:java并发编程实战</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/03/22/java/lock()与lockInterruptibly()的区别/" rel="next" title="lock()与lockInterruptibly()的区别">
                <i class="fa fa-chevron-left"></i> lock()与lockInterruptibly()的区别
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/03/22/java/NIO和BIO和AIO/" rel="prev" title="NIO, AIO和BIO">
                NIO, AIO和BIO <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">xiezc</p>
              <p class="site-description motion-element" itemprop="description">主要一些技术文章, 有些文章是转载的</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">72</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#CountDownLatch-与-CyclicBarrier-区别"><span class="nav-number">1.</span> <span class="nav-text">CountDownLatch 与 CyclicBarrier 区别.</span></a></li></ol><li class="nav-item nav-level-1"><a class="nav-link" href="#写在前面"><span class="nav-number"></span> <span class="nav-text">写在前面</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#闭锁"><span class="nav-number"></span> <span class="nav-text">闭锁</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#信号量"><span class="nav-number"></span> <span class="nav-text">信号量</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#栅栏"><span class="nav-number"></span> <span class="nav-text">栅栏</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#阻塞队列"><span class="nav-number"></span> <span class="nav-text">阻塞队列</span></a></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xiezc</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("eRAHvO0xVYwckgdXIVpfugRG-gzGzoHsz", "57lKp708hde92YeG1xX9MQj1");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

</body>
</html>
